/*
 * physical.js
 * 物理量
 */
;
(function (call) {
	var main = {
		baseUrl: CafeJS.CXT,
		mapId: "tjMap",
		playList: null,
		datepicker: null,
		legendpicker: null,
		echartOption: {},
        echartObj: Object,
		router: {
			getPhysicalData: 'zhfx/phy/skPhy',
			getPhysicalStatData: 'zhfx/phy/skPhyStaByTime',
			getLatestTime: 'zhfx/phy/skPhy/LatestTime',
			getSkPhyStaByTimes: '/zhfx/phy/skPhyStaByTimes',
			productcfg: "/business/common/json/product.json"
		},
		init: function () {
			this.initView();
		},
		initView: function () {
            var that = this;
			that.initDatePicker();
			that.getLatestTime();
			that.echartOption = {
				title: {
					text: '过去24小时变化趋势',
					x: 'center',
					top: 20
				},
				xAxis: {
					type: "category",
					axisTick: {
						show: false
					},
					axisLabel: {
						textStyle: { 
							//改变刻度字体样式
							color: function (value, index) {
								var date = new Date(value);
								var hour  = date.getHours();
								hour = hour>9?hour+"":"0"+hour;
								var day = date.getDate();
								day = day>9?day:"0"+day;
								if((hour === "23" && index != 24) || index === 24){
									return "red";
								}else{
									return "#333333";
								}
							},
							fontSize: 12
						},
						formatter: function (value,index) {
							var date = new Date(value);
							var hour  = date.getHours();
							hour = hour>9?hour+"":"0"+hour;
							var day = date.getDate();
							day = day>9?day:"0"+day;
							if((hour === "23" && index != 24) || index === 24){
								return hour+":00\n"+day+"日";
							}else{
								return hour+":00";
							}
						}
					},
					data: []
				},
				tooltip: {
					trigger: "axis",
					textStyle: {
						fontSize: 13
					},
					formatter: function (params) {
						return that.showTooltip(params,this)
					},
					padding: 8
				},
				legend: {
					show: true,
					icon: "roundRect",
					itemWidth: 20,
					itemHeight: 10,
					itemGap: 15,
					top: 50,
					right: 20,
					data: [],
					textStyle: {
						color: "#333333",
						fontSize: 14
					}
				},
				grid: {
					show: true,
					bottom: "5%",
					top: "15%",
					left:"3%",
					right:"2%",
					containLabel: true,
					borderWidth: 0
				},
				yAxis: [
					{
						type: "value",
						name:"%",
						axisLabel: {
							formatter: "{value}",
							textStyle: {
								fontSize: 12
							}
						},
						splitNumber: 10,
						axisLine: {
							show: true,
						}
					}
				],
				series: [
					{
						name: "",
						data: [],
						type: "line",
						smooth: true,
						symbol: 'circle',
						symbolSize: 5,
						showAllSymbol: true
					}
				]
			};
		},
		// 获取自动站最新实况时间
		getLatestTime: function () {
			var that = this;
            if($("#userInfo").data("isMatchuser")){
                that.datepicker.setVal('2022-07-26 11:00:00');
                $.getJSON(that.router.productcfg, function (cfg) {
					that.initProductList(cfg);
				})
                return;
            }
			$.ajax({
				url: this.router.getLatestTime,
				type: 'GET',
				data: {
					element: 'CAPE'
				},
				dataType: 'json',
			}).done(function (res) {
				if (res.isSuccess && res.data) {
					that.datepicker.setVal(res.data);
				}
				$.getJSON(that.router.productcfg, function (cfg) {
					that.initProductList(cfg);
				})
			})
        },
		// 初始化产品列表
		initProductList: function (cfg) {
			var that = this
			var params = {
				container: '.product-content.physical',
				data: cfg.physical,
				eleClick: function (ele, oldEle, selected) {
					var oldId = oldEle.ele_id; // 上一个选中要素
					var name = ele.ele_name;
					var ptype = ele.type; //当前要素的类型
					that.clearLayer([ptype]);
					var pro = {
						name: '物理量_' + name,
						time: that.calcStartTime(ele),
						bussitype: 'physical',
						ele: ele,
						isGrid: false,
						isSK: true
					}
					if (selected) {
						// 增加产品图层
						that.addLayerManage(pro);
						that.queryEleData(ele, pro.time);
					} else {
						CafeJS.layerManage.removeLayer(pro); // 删除当前要素的图层
					}
				},
				gridClick: function (ele, oldEle, selected) {
					var eleid = ele.ele_id; //当前要素id
					var oldId = oldEle.ele_id; // 上一个选中要素
					var ptype = ele.type; //当前要素的类型
					var name = ele.ele_name;

					that.clearGridLayer(oldId);

					var pro = {
						name: '物理量_' + name + '（格）',
						time: that.calcStartTime(ele),
						bussitype: 'physical',
						ele: ele,
						isGrid: true,
						isSK: true
					}
					if (selected) {
						// 增加产品图层
						that.addLayerManage(pro);
						that.queryRawGridData(ele, pro.time);

						if (oldId != eleid) {
							name = '物理量_' + oldEle.ele_name + '（格）';
							CafeJS.layerManage.removeLayer({ name: name }); // 删除上一个选中要素的图层
						}
					} else {
						CafeJS.layerManage.removeLayer(pro); // 删除当前要素的图层
					}
				}
			};
			CafeJS.analysis(params);
		},
		//点击站点出现chart图
		showEchart: function (id,eleName,unit) {
			var that = this;
			if (CafeJS.ModalBoxExist(id)) {
				CafeJS.ModalBoxClose(id);
			}
			CafeJS.ModalBox({
				id: id,
				container: 'cafe-busis-container',
				title: "变化趋势",
				width: 1300,
				height: 650,
				m_top: 90,
				m_right: 200,
				hasMask:true,
				hide: true,
				html: "<div id='physical-echart'></div>",
				showCall: function(obj) {
                	that.drawEchart(eleName,unit);
                },
				closed: function () { }
			});
		},
		drawEchart:function(eleName,unit){
			var that = this;
			that.echartObj = echarts.init(document.getElementById("physical-echart"));
			that.echartObj.clear();
			that.echartOption.legend.name = eleName;
			that.echartOption.series[0].name = eleName;
			that.echartOption.yAxis[0].name = unit;
			that.echartOption.legend.data = [eleName];
			that.echartObj.setOption(that.echartOption, true);
		},
		showTooltip:function(params){
			var str = '<div style="display: flex;align-items: center"><div style="background-color: red;height: 10px;width: 10px;border-radius: 50%;margin-right: 6px"></div>';
			return params[0].name+"<br>"+str+params[0].seriesName+"："+params[0].value+"("+this.echartOption.yAxis[0].name+")";
		},

		// 初始化时间控件
		initDatePicker: function () {
			var _this = this;
			this.datepicker = CafeJS.Datepicker({
				appendTo: "#datepicker-physical",
				type: 3,
				dateFmt: 'yyyy-MM-dd hh',
				dateType: 'H',
				timeInterval: 1,
				call: function () {
					_this.queryMultiEleData();
				}
			});
			$("#datepicker-physical").show();
		},
		// 初始化图例
		initLegentpicker: function (ele, appendTo) {
			var that = this;
			var layers = that.getModels(ele);
			var layerIds = [];
			$.each(layers, function (i, m) {
				layerIds.push(m.id);
			});
			CafeJS.legentPicker = CafeJS.Legentpicker({
				appendTo: appendTo,
				gisId: that.mapId,
				layerId: layerIds,
				totalWidth: 400,
				h_legend: 15,
				seq: 'decrease',
				productId: ele.ele_id,
				isShowSlider: false
			});
		},
		// 初始化播放列表
		initPlayList: function (pro) {
			var that = this;
			var startTime = pro.time;

			var layers = this.getModels(pro.ele);
			var interval = pro.ele.interval || 60;
			this.playList = CafeJS.Timeline3({
				appendTo: "#a-m-timeline",
				curDate: startTime,
				type: 1,
				pro: pro,
				dateOpt: {
					dateFmt: 'yyyy-MM-dd hh:mm',
					timeInterval: interval
				},
				timeInterval: interval,
				layers: layers,
				gisId: that.mapId,
				call: function (pro) {
					CafeJS.layerManage.updateLayer(pro);
					var ele = pro.ele;
					if (pro.isGrid) {
						that.queryRawGridData(ele, pro.time);
					} else
						that.queryEleData(ele, pro.time);
				},
				getPlayData: function (pro, timeArr) {
					if (pro.isGrid) {
						var ele = pro.ele;
						that.queryRawGridData(ele, timeArr);
					}
				}
			});
		},
		// 查询已选择要素
		queryMultiEleData: function () {
			var that = this;
			var pro, time;
			$(".physical .product-list li.active").each(function (i, ele) {
				pro = $(ele).data('pro');
				time = that.calcStartTime(pro);
				CafeJS.layerManage.updateLayerTime(time, 'physical', null, pro.ele_id);
				that.queryEleData(pro, time);
			});
			$(".physical .product-list i.active").each(function (i, ele) {
				pro = $(ele).parent().data('pro');
				time = that.calcStartTime(pro);
				CafeJS.layerManage.updateLayerTime(time, 'physical', null, pro.ele_id);
				that.queryRawGridData(pro, time);
			});
		},

		// 查询要素数据
		queryEleData: function (ele, time) {
			var that = this;
			var ptype = ele.type;
			that.clearLayer([ptype]);
			that.queryRawStatData(ele, time);
		},
		//查询站点数据
		queryRawStatData: function (ele, time) {
			var that = this;
			time = new Date(time).format('yyyy-MM-dd hh:mm:ss');
			var element = ele.ele_id;
			$.ajax({
				url: that.router.getPhysicalStatData,
				type: "GET",
				data: {
					element: element,
					skTime: time
				},
				contentType: 'application/json',
				success: function (res) {
					if (!res.isSuccess) return;
					var data = res.data;
					if (!data || data.length === 0) {
						alert("该时间点没有数据");
						return;
					}
					var eleType = ele.type;
					var arr = [];
					for(var i=0;i<data.length;i++){
						var station = {};
						station["val"] = Number(data[i].val).toFixed(1);
						station["lat"] = Number(data[i]["lat"]);
						station["lon"] = Number(data[i]["lon"]);
						station["stationName"] = data[i]["stationName"];
						station["stationId"] = data[i]["stationId"];
						station["options"] = {
							labelStyle: $.extend(false, { fillStyle: that.getLabelObj(eleType).scolor, size: 14, textAlign: "center" }, that.getLabelObj(eleType)),
							bgStyle: { fillStyle: "rgba(0,0,0,0)", strokeStyle: "rgba(0,0,0,0)", radius: 3 }
						}
						arr.push(station);
					}
					var dataArr = {};
                        dataArr[0] = {};
                        dataArr[0]["physic"] = arr;
					var dataObj = {
						dataArr: dataArr,
						eleTypes: [eleType],
						statTypes: [0]
					}
					GIS.Station.showElements(that.mapId, dataObj, that.getStatStyleObj(),that.getLabelObj(eleType), null, null, { 'cx': true });
					// 站点详情
					GIS.MouseEvent.Bind(that.mapId, "physic0Stat", function(stationInfo) {
						that.getDataArrByTimes(time,ele,stationInfo.stationId,stationInfo.stationName);
					}, function(stationInfo) {
						return stationInfo.stationName;
					});
				},
				error: function () {
					loading.remove();
				}
			})
		},
		// 获取站点类型样式
		getStatStyleObj: function () {
			var styleObj = {
				minLevel: 0,
				size: 8,
				font: { color: { a: 1, r: 1, g: 0, b: 0 }, xOffset: 0, yOffset: 20, size: '16px', length: 26, width: 8 }
			};
			return {
				//基本站
				0: $.extend(false, styleObj, { color: { r: 0, g: 0, b: 0, a: 255 }, size: 8 }),
				//区域站
				1: $.extend(false, styleObj, { color: { r: 0, g: 0, b: 0, a: 255 }, size: 8 }),
				//海岛站
				2: $.extend(false, styleObj, { color: { r: 0, g: 0, b: 0, a: 255 }, size: 8 }),
				//浮标站
				3: $.extend(false, styleObj, { color: { r: 0, g: 0, b: 0, a: 255 }, size: 8 }),
				//船舶站
				4: $.extend(false, styleObj, { color: { r: 0, g: 0, b: 0, a: 255 }, size: 8 }),
				//平台站
				5: $.extend(false, styleObj, { color: { r: 0, g: 0, b: 0, a: 255 }, size: 8 })
			};
		},
		// 获取要素样式
		getLabelObj: function (eleType) {
			var labelObj = {
				"physic": { color: { R: 0, G: 0 ,B: 0, A: 1 },scolor: "rgb(0,0,0)" , lineWidth : 1, offx : -20, offy : 0, size : 16}
			}
			return labelObj[eleType];
		},
		//点击物理量站点时间段数据
		getDataArrByTimes:function(time,ele,stationId,stationName){
			var that = this;
			var date = new Date(time);
			var endTime = date.format('yyyy-MM-dd hh:mm:ss');
			var startTime = new Date(date.setDate(date.getDate() - 1)).format('yyyy-MM-dd hh:mm:ss');
			var element = ele.ele_id;
			$.ajax({
				url: that.router.getSkPhyStaByTimes,
				type: "GET",
				data: {
					element: element,
					startTime: startTime,
					endTime: endTime,
					stationId:stationId
				},
				contentType: 'application/json',
				success:function(res){
					if (!res.isSuccess) return;
					var data = res.data;
					if (!data || JSON.stringify(data) == "{}") return;
					var arr = [];
					for(var time in data){
						arr.push({"time":time,"data":data[time]});
					}
					arr.sort(function(a,b){
						return new Date(a.time).getTime() - new Date(b.time).getTime();
					})
					var xAxisArr = [];
					var seriesArr = [];
					for(var j=0;j<arr.length;j++){
						xAxisArr.push(arr[j].time);
						if(arr[j].data.length === 0){
							seriesArr.push("");
						}else{
							seriesArr.push(arr[j].data[0].val);
						}
					}
					that.echartOption.xAxis.data = xAxisArr;
					that.echartOption.series[0].data = seriesArr;
					that.echartOption.title.text = stationName+"过去24小时"+ele.ele_name+"变化趋势";
					that.showEchart("stateEchart",ele.ele_name,ele.unit);
				}
			})
		},
		//查询格点数据
		queryRawGridData: function (ele, time) {
			var that = this;
			var element = ele.ele_id;
			if (!element) return;

			if (time.indexOf(',') == -1) {
				time = new Date(time).format('yyyy-MM-dd hh:mm:ss');
			}
			var param = {
				skTimes: time,
				element: element,
				min: -100,
				max: 10000
			}
			CafeJS.ajax({
				url: that.router.getPhysicalData,
				params: param,
				type: "GET",
				success: function (e) {
					var arrayBuffer = e.response;
					if (arrayBuffer.byteLength === 0) {
						alert("该时间点没有数据");
						that.clearGridLayer(ele.ele_id);
						return;
					}
					that.drawGridRawMap(arrayBuffer, ele);
				}
			})
		},
		// 绘制格点色斑图
		drawGridRawMap: function (data, ele) {
			var typeArr = this.getModels(ele);

			var colorObj = CafeJS.Legentconfig().cfg()[ele.ele_id];

			// 显示色斑和数值
			GIS.GridShow.showGrid(this.mapId, typeArr, data, {}, colorObj);
			CafeJS.legentPicker.updateLegentRange(typeArr,this.mapId);
		},
		// 增加产品图层
		addLayerManage: function (pro) {
			var that = this;
			if (CafeJS.layerManage) {
				CafeJS.layerManage.addLayer(pro);
			} else {
				CafeJS.layerManage = CafeJS.LayerManage({
					appendTo: "#c-b-layermanage",
					mapId: that.mapId,
					proInfo: pro,
					call: function (pro) {
						CafeJS[pro.bussitype].initPlayList(pro);
					},
					more: function (pro) {
						CafeJS[pro.bussitype].stationView(pro);
					},
					close: function (pro) {
						CafeJS[pro.bussitype].delLayer(pro);
					}
				})
			}
			if (pro.isGrid && !pro.ele.models.includes("isoline"))
				that.initLegentpicker(pro.ele, '.cafe-layer-item.active');
		},
		// 根据时间间隔获取开始时间
		calcStartTime: function (ele) {
			var time = new Date(this.datepicker.getVal());
			switch (ele.interval) {
				case 60:
					time.setMinutes(0);
					break;
			}
			return time.format('yyyy-MM-dd hh:mm');
		},
		// 清除单要素GIS图层
		clearLayer: function (eleid) {
			GIS.Station.eleShowControl(this.mapId, [0, 1, 2, 3, 4, 5], eleid, "delete");
		},
		// 删除图层后取消要素选择
		delLayer: function (pro) {
			var eleid = pro.ele.ele_id;
			if (pro.isGrid) {
				var $grid = $(".physical .product-list i.active");
				if ($grid.parent().data('eleid') == eleid)
					$grid.click();
				return false;
			}
			$(".physical .product-list li.active").each(function () {
				if ($(this).data('eleid') == eleid) {
					$(this).click();
					return false;
				}
			})
		},
		// 清除格点GIS图层
		clearGridLayer: function (eleid) {
			var layerIds = [];
			GLMap.layerIds.forEach(function (layerId) {
				if (layerId.indexOf('physical-layer') != -1 && layerId.lastIndexOf(eleid) != -1) {
					layerIds.push(layerId);
				}
			})
			GIS.LayerControll.deleteLayer(this.mapId, layerIds);
		},
		// 获取要素样式
		getModels: function (ele) {
			var models = [];
			$.each(ele.models.split(","), function (i, m) {
				var layerId = "physical-layer-" + m + "-" + ele.ele_id;
				models.push({
					type: m,
					visible: true,
					uv: false,
					wd: true,
					cacheConfig: 'noCache',
					id: layerId
				});
			});
			return models;
		}
	};
	if (typeof call === 'function') {
		CafeJS.physical = main;
		call(main);
	}

})(function (main) {
	CafeJS.models(['datepicker', 'moddialogNew', 'legentpicker', 'legentconfig', 'ajax', 'timeLine3'], function () {
		main.init();
	});
});
